﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace RXY_Mall.Core
{
    public class CommonHelper
    {
        public static Dictionary<int, DateTime> DownloadOrder = new Dictionary<int, DateTime>();
        /// <summary>
        /// 获取当前系统的根目录路径
        /// </summary>
        /// <remarks>Create By Scenery 2012-12-11</remarks>
        /// <returns></returns>
        public static string GetRootPath
        {
            get
            {
                return System.AppDomain.CurrentDomain.BaseDirectory;
            }
        }

        /// <summary>
        /// 检查分页
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        public static void CheckPage(ref int pageIndex, ref int pageSize)
        {
            if (pageIndex <= 0)
                pageIndex = 1;
            if (pageSize <= 0)
                pageSize = 20;
            if (pageSize > 100)
                pageSize = 100;
        }

        /// <summary>
        /// 字符串转化成List<int>
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static List<int> StringConvertListOfInt(string str)
        {
            List<int> list = null;
            try
            {
                if (string.IsNullOrEmpty(str))
                {
                    return list;
                }
                List<string> listOfStrings = new List<string>(str.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries));
                list = listOfStrings.Select<string, int>(q => Convert.ToInt32(q)).ToList();
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
            }
            return list;
        }

        /// <summary>
        /// 将指定的字符串进行MD5加密码
        /// </summary>
        /// <param name="input">需要加密的字符串</param>
        /// <remarks>Create By Scenery 2014/08/28</remarks>
        /// <returns>加密后的字符串</returns>
        public static string GetMd5Hash(string input)
        {
            // Create a new instance of the MD5CryptoServiceProvider object.
            MD5 md5Hasher = MD5.Create();

            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hasher.ComputeHash(Encoding.UTF8.GetBytes(input));

            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data 
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            // Return the hexadecimal string.
            return sBuilder.ToString();
        }

        public static string GetMD5(string str)
        {
            MD5 md5 = MD5.Create();
            //需要将字符串转成字符数组
            byte[] buffer = Encoding.UTF8.GetBytes(str);
            byte[] md5Buffer = md5.ComputeHash(buffer);
            StringBuilder sb = new StringBuilder(32);
            for (int i = 0; i < md5Buffer.Length; i++)
            {
                sb.Append(md5Buffer[i].ToString("x2"));//把一个byte转换成一个2位的16进制值
            }
            return sb.ToString();
        }

        #region ========加密========

        /*
            string strPre = "曾经沧海难为水";
            string key = "love1314";
            Console.WriteLine("加密前:"+strPre);
            var strTemp = IceEncrypt.Encrypt(strPre, key);
            Console.WriteLine("加密后:"+strTemp);
            var decStr = IceEncrypt.Decrypt(strTemp, key);
            Console.WriteLine("解密后:" + decStr);
         */

        /// <summary>
        /// 加密数据
        /// </summary>
        /// <param name="Text">要加密的内容</param>
        /// <param name="sKey">密匙</param>
        /// <returns>加密后的字符串结果</returns>
        public static string Encrypt(string Text, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray = Encoding.Default.GetBytes(Text);
            des.Key = Encoding.ASCII.GetBytes(GetMD5(sKey).Substring(0, 8));
            des.IV = Encoding.ASCII.GetBytes(GetMD5(sKey).Substring(0, 8));
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            return ret.ToString();
        }
        
        #endregion

        #region ========解密========
        
        /// <summary> 
        /// 解密数据 
        /// </summary> 
        /// <param name="Text">要解密的内容</param> 
        /// <param name="sKey">密匙</param> 
        /// <returns>解密后的字符串结果</returns> 
        public static string Decrypt(string Text, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            int len = Text.Length / 2;
            byte[] inputByteArray = new byte[len];
            int x, i;
            for (x = 0; x < len; x++)
            {
                i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);
                inputByteArray[x] = (byte)i;
            }
            des.Key = Encoding.ASCII.GetBytes(GetMD5(sKey).Substring(0, 8));
            des.IV = Encoding.ASCII.GetBytes(GetMD5(sKey).Substring(0, 8));
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            return Encoding.Default.GetString(ms.ToArray());
        }

        #endregion
    }
}
